package com.uye.framework.command;

import java.util.HashMap;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.uye.framework.dto.IJSONRequest;
import com.uye.framework.exception.CommandConfigurationException;
import com.uye.framework.exception.CommandNotFoundException;

/**
 * Factory responsible for converting a JSON string into the appropriate
 * ICommand object. Detailed parsing is deferred through JSON Deserialization.
 * 
 * @author uye
 */
@SuppressWarnings("rawtypes")
public class ServiceCommandFactory extends
		CommandFactory<BaseStatefulJSONCommand, IJSONRequest> {
	
	private Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private BeanFactory beanFactory;
	
	public BaseStatefulJSONCommand getCommandFromJSONString(String json)
			throws CommandNotFoundException {

		@SuppressWarnings("rawtypes")
		HashMap request = (HashMap) (JSONObject.toBean(
				JSONObject.fromObject(json), HashMap.class));

		// TODO add logic here to prep the form and add to a new command
		// instance

		String serviceName = (String) request.get("serviceName");
		Class<BaseStatefulJSONCommand> commandClass = getCommand( serviceName );
		BaseStatefulJSONCommand commandInstance;
		try {
//			commandInstance = commandClass.newInstance();
			commandInstance = beanFactory.getBean(commandClass);
			Class<? extends IJSONRequest> requestModelClass = getModel(serviceName);
					

			if (null == requestModelClass) {
				throw new CommandConfigurationException("Could not assign a model for the service " +serviceName  );
			}else{
				logger.debug("Using model :"+ requestModelClass.getCanonicalName()+" for service request: "+ serviceName);
			}

			IJSONRequest requestModel = requestModelClass.cast((JSONObject
					.toBean(JSONObject.fromObject(json), requestModelClass)));
			
			commandInstance.setModel(requestModel);

//		} catch (InstantiationException e) {
//			throw new CommandNotFoundException(
//					"Could not create a new instance of "
//							+ commandClass.getName(), e);
//		} catch (IllegalAccessException e) {
//			throw new CommandNotFoundException(
//					"Could not create a new instance of "
//							+ commandClass.getName(), e);
//		
			
		}finally{}
		return commandInstance;
	}

}
